
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="scroll scrollbar-sty">
      <el-button @click="addUser" type="primary">添加用户</el-button>
      <el-table
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        :data="tableData"
        :header-cell-style="{
          color: '#606266',
          textAlign: 'center',
        }"
        :cell-style="{ textAlign: 'center', padding: '5px 0', height: '30px' }"
        :row-style="{ height: '48px' }"
        empty-text="Current page has no data"
      >
        <!-- 展开列表 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="deleteRolesById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 三级权限-->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRolesById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-row
                      :class="[i3 === 0 ? '' : '']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                    >
                      <el-col>
                        <el-tag
                          type="warning"
                          closable
                          @close="deleteRolesById(scope.row, item3.id)"
                        >
                          {{ item3.authName }}
                        </el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>
                  <!-- {{scope.row}} -->
              </pre>
          </template>
        </el-table-column>
        <!-- 索引列表 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作" prop="">
          <template slot-scope="scope">
            <el-row>
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="EidtTableRow(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="e-icon-delete"
                size="mini"
                @click="deleteTableRow(scope.row.id)"
                >删除</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightDialog(scope.row)"
                >分配权限</el-button
              >
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :total="pageInfo.total"
        :page-sizes="[10, 20]"
        :page-size="pageInfo.pageSize"
        style="float: right"
        @current-change="changeCurrentPage"
        @size-change="changeSizePage"
      >
      </el-pagination> -->
    </el-card>

    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancelButton" @click="closeForm('ruleForm')"
          >cancel</el-button
        >
        <el-button type="primary" @click="submitForm('ruleForm')"
          >confirm</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialog"
      width="30%"
      :before-close="handleCloseRight"
    >
      <el-tree
        class="rightTree"
        :data="rightsList"
        :props="defaultProps"
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        :show-checkbox="true"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialog = false">取 消</el-button>
        <el-button type="primary" @click="setRightSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 树形结构带按钮 -->
    <div>
      
    </div>
  </div>
  
</template>

<script>
export default {
  name: '',
  data() {
    return {
      pageInfo: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      tableData: [],
      type: 'tree',
      tableLoading: false,
      dialogVisible: false,
      setRightDialog: false,
      timer: null,
      ruleForm: {
        roleName: '',
        roleDesc: '',
      },
      rules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
      },
      rightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      //默认选中的节点
      defKeys: [],
      //分配权限id
      roleId:''
    }
  },
  created() {
    // this.getRightsList()
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      this.tableData = res.data
      // console.log(res.data)
    },
    //删除
    deleteTableRow(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await this.$http.delete('roles/' + id)
          this.getRolesList()
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //添加用户
    addUser() {
      this.dialogVisible = true
    },
    //编辑
    EidtTableRow() {},
    //分配权限
    distribution() {},

    // 关闭
    handleClose(done) {
      this.dialogVisible = false
      // this.dialogVisibleEdit = false
      this.ruleForm = {}
    },
    //确认
    submitForm(ruleForm) {
      //防抖处理
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.$refs[ruleForm].validate(async (valid) => {
          if (valid) {
            const { data: res } = await this.$http.post('roles', this.ruleForm)
            this.$message.success('添加用户成功!')
            this.ruleForm = {
              roleName: '',
              roleDesc: '',
            }
            this.getRolesList()
            this.dialogVisible = false
          }
        })
      }, 500)
      // const { data: res } = this.$refs[ruleForm].resetFields()
    },
    // 取消
    closeForm(ruleForm) {
      this.$refs[ruleForm].resetFields()
      this.dialogVisible = false
    },
    //删除权限
    deleteRolesById(role, rightId) {
      this.$confirm('此操作将永久该用户此权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      // console.log(role.children);
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          role.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //分配权限
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get('rights/' + this.type)
      this.rightsList = res.data //获取到的树形结构数据给rightsList
      //递归获取三级节点的Id
      this.defKeys = [] //清除上一次关闭窗口重复的id
      this.getLeafkeys(role, this.defKeys)
      // console.log(this.defKeys)
      this.setRightDialog = true
    },
    //关闭setRightDialog
    handleCloseRight() {
      this.setRightDialog = false
    },
    //递归 获取角色所有三级权限的id并保存到defKeys 数组中
    getLeafkeys(node, arr) {
      //如果不包含children 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getLeafkeys(item, arr))
    },
    //分配权限确定
     async setRightSubmit() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), //返回选中的节点
        ...this.$refs.treeRef.getHalfCheckedKeys() //返回选中节点的父亲节点
      ]

      // console.log(keys);
      // console.log(keys.join(','));
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids : keys.join(',')})
      if(res.meta.status == 200){
        this.$message.success('分配权限成功')
        this.setRightDialog = false
      }else {
        this.$message.error();('分配权限失败')
        this.setRightDialog = false
      }
      // this.getRolesList()
      
    },
  },
}
</script>

<style lang="less" scoped>
.scroll {
  height: calc(100vh - 90px);
  overflow-y: auto;
  overflow-x: hidden;
}
.input-with-select {
  width: 300px;
  margin-right: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
}
.search_input {
  width: 400px;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  // justify-content: center;
  align-items: center;
}
.rightTree {
  margin-left: 30px;
}
</style>